﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.YouTube;
using Google.GData.Client;
using FlickrNet;
using Resources;
using Google.GData.Photos;
using System.Xml;
using System.Net;
using System.IO;

public partial class Controls_WebContent : System.Web.UI.UserControl
{
    public string SearchPhrase { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {

            try
            {
                //show news from google        
                GoogleNewsDataSource.DataFile = string.Format(GoogleHelper.GoogleNewsFeedUrl, SearchPhrase);
                GoogleNewsListView.DataSourceID = GoogleNewsDataSource.UniqueID;
                GoogleNewsListView.DataBind();

            }
            catch (Exception)
            {
                
               

            }
            try
            {
                //show blogsearch
                XmlDocument doc = new XmlDocument();

                /*
                 The follow code was patched on 2011-05-30 by user Mindwalker
                 to fix the bug noticed at http://aspnetrsstoolkit.codeplex.com/discussions/259548
             
                 The code was changed to first attempt to use the XmlDocument.Load function, as it
                 had previously done, but upon encountering parsing exception, it will attempt
                 to load the URL into a string first, using function LoadUrl (added above) and then 
                 call XmlDocument.Load on a stream generated from the string. For some reason, the 
                 XmlDocument.Load was failing for certain feeds when loading directly from a remote
                 URL.
             
                 It might be advisable to change this code to always load the remote URL into a string 
                 and then call the XmlDocument.Load, rather than only doing that if the XmlDocument.Load
                 from the remote URL failed. I didn't change it to do that, in case there was some
                 advantage to loading it directly when possible.             
                 */
                string url = string.Format(GoogleHelper.BlogSearchFeedUrl, SearchPhrase);
                try
                {
                    doc.Load(url);
                }
                catch (System.Xml.XmlException)
                {
                    // If it failed to parse, try loading the document into a string then parsing from that.
                    string html = LoadUrl(url);
                    XmlTextReader reader = new XmlTextReader(new StringReader(html));
                    doc.Load(reader);
                    reader.Close();
                }




                BlogSearchDataSource.Data = doc.OuterXml;
                BlogSearchDataSource.DataBind();
                BlogSearchListView.DataSource=BlogSearchDataSource;
                
                BlogSearchListView.DataBind();
            }
            catch (Exception)
            {

               
            }


            //show news from live com
            try
            {
                LiveNewsDataSource.DataFile = string.Format(LiveHelper.LiveNewsFeedUrl, SearchPhrase);
                LiveNewsListView.DataSourceID = LiveNewsDataSource.UniqueID;
                LiveNewsListView.DataBind();
            }
            catch (Exception)
            {

                //todo;
            }


            //search results from live.com
            try
            {
                LiveSearchDataSource.DataFile = string.Format(LiveHelper.LiveSearchFeedUrl, SearchPhrase);
                LiveSearchListView.DataSourceID = LiveSearchDataSource.UniqueID;
                LiveSearchListView.DataBind();
            }
            catch (Exception)
            {

                //todo
            }



            try
            {
                LoadVideos(this.SearchPhrase);


            }
            catch (Exception)
            {


            }
            SetTheCorrectTabIndex();
            if (VideosListView.Items.Count > 0)
            {
                VideosListView.SelectedIndex = 0;
                VideosListView_SelectedIndexChanged(VideosListView, new EventArgs());
            }

        }


    }

    private static string LoadUrl(string url)
    {
        StreamReader sr = null;
        try
        {
            HttpWebRequest myRequest = (HttpWebRequest)(System.Net.WebRequest.Create(url));
            HttpWebResponse myResponse = (HttpWebResponse)(myRequest.GetResponse());
            sr = new System.IO.StreamReader(myResponse.GetResponseStream());
            return sr.ReadToEnd();
        }
        finally
        {
            if (sr != null)
            {
                sr.Dispose();
            }
        }
    }

    private void SetTheCorrectTabIndex()
    {
        if (SearchPhrase.ToLower().Contains("image") || SearchPhrase.ToLower().Contains("picture") || SearchPhrase.ToLower().Contains("photo"))
        {
            MainTabContainer.ActiveTabIndex = 1;
        }
        else if (SearchPhrase.ToLower().Contains("video") || SearchPhrase.ToLower().Contains("movie") || SearchPhrase.ToLower().Contains("trailer") || SearchPhrase.ToLower().Contains("episode") || SearchPhrase.ToLower().Contains("film"))
        {
            MainTabContainer.ActiveTabIndex = 3;
        }
        else if (GoogleNewsListView.Items.Count == 0)
        {
            MainTabContainer.ActiveTabIndex = 5;
            if (LiveSearchListView.Items.Count == 0)
            {
                MainTabContainer.ActiveTabIndex = 4;
                if (BlogSearchListView.Items.Count == 0)
                {
                    MainTabContainer.ActiveTabIndex = 3;
                }
            }

        }
    }

    private void LoadFlickerImages()
    {
        Photos photos = FlickrHelper.GetPhotosByKeyword(this.SearchPhrase);
        FlickerImagesListView.DataSource = photos.PhotoCollection;
        FlickerImagesListView.DataBind();
    }

    private void LoadPicasaImages()
    {
        AtomEntryCollection images = PicasaHelper.GetImagesByPhrase(this.SearchPhrase);
        PicasaImagesListView.DataSource = images;
        PicasaImagesListView.DataBind();
    }

    private void LoadVideos(string keyword)
    {
        try
        {
            string username = "seniordotnetdeveloper@gmail.com";
            string password = "dessi77&";
            string application = "buzzhour";
            string clientID = "ytapi-NikolayYordanov-buzzhour-673umn97-1";
            string developerKey = "AI39si65gkXT57qFsN8zVZiAMVRpySX9h_TVRKBS5F3bGrO0c06YuF6ISMhX2BQZyZp2MxMa_JOtcftvSeiA1kqIpzN2CulfYA";

            YouTubeService service = new YouTubeService(application, clientID, developerKey);
            service.setUserCredentials(username, password);

            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.Query = keyword;
            query.NumberToRetrieve = 18;
            YouTubeFeed videoFeed = service.Query(query);
            VideosListView.DataSource = videoFeed.Entries;
            VideosListView.DataBind();
            if (videoFeed.Entries.Count > 0)
            {
                VideosListView.SelectedIndex = 0;
                VideosListView_SelectedIndexChanged(VideosListView, new EventArgs());
            }
        }
        catch (Exception)
        {

        }

    }


    protected void VideosListView_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (VideosListView.Items[VideosListView.SelectedIndex].ItemType == ListViewItemType.DataItem)
        {

            ListViewDataItem data = VideosListView.Items[VideosListView.SelectedIndex] as ListViewDataItem;
            ImageButton VideoThumbNail = VideosListView.Items[VideosListView.SelectedIndex].FindControl("VideoThumbNail") as ImageButton;
            VideoPlayerSource.Text = ComplexStrings.YouTubePlayerNormalSize.Replace("MovieId", VideoThumbNail.DescriptionUrl);

            Label videoTitle = VideosListView.Items[VideosListView.SelectedIndex].FindControl("VideoTitle") as Label;
            VideoTitleLabel.Text = videoTitle.Text;


        }

    }

    protected void PicasaImagesListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            PicasaEntry picasaImage = dataItem.DataItem as PicasaEntry;
            Image ImageThumbNail = e.Item.FindControl("ImageThumbNail") as Image;
            ImageThumbNail.ImageUrl = picasaImage.Media.Thumbnails[2].Url;
            ImageThumbNail.Attributes.Add("onclick", string.Format("window.open('{0}',null,'width=650','height=350','status=yes,toolbar=no,menubar=no,location=no,resizable=yes')", ImageThumbNail.ImageUrl.Replace("s288", "s800")));
            Label ImageTitle = e.Item.FindControl("ImageTitle") as Label;
            ImageTitle.Text = picasaImage.Summary.Text;

        }
    }

    protected void VideosListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem data = e.Item as ListViewDataItem;
            YouTubeEntry entry = data.DataItem as YouTubeEntry;
            ImageButton VideoThumbNail = e.Item.FindControl("VideoThumbNail") as ImageButton;
            Label VideoTitle = e.Item.FindControl("VideoTitle") as Label;
            VideoTitle.Text = entry.Title.Text;
            VideoThumbNail.ImageUrl = entry.Media.Thumbnails[0].Url;
            try
            {
                VideoThumbNail.DescriptionUrl = entry.Media.VideoId.Value;
            }
            catch (Exception)
            {

            }


        }
    }

    protected void VideosListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
    {
        if (VideosListView.Items[VideosListView.SelectedIndex].ItemType == ListViewItemType.DataItem)
        {
            VideosListView.SelectedIndex = e.NewSelectedIndex;

            e.Cancel = false;

        }
    }


    protected void FlickerImagesListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            Photo flickrImage = dataItem.DataItem as Photo;
            Image ImageThumbNail = e.Item.FindControl("ImageThumbNail") as Image;
            ImageThumbNail.ImageUrl = flickrImage.SmallUrl;
            ImageThumbNail.Attributes.Add("onclick", string.Format("window.open('{0}',null,'width=650','height=350','status=yes,toolbar=no,menubar=no,location=no,resizable=yes')", flickrImage.MediumUrl));
            Label ImageTitle = e.Item.FindControl("ImageTitle") as Label;
            ImageTitle.Text = flickrImage.Title;

        }
    }

    protected void ActiveTabChanged(object sender, EventArgs e)
    {
        if (MainTabContainer.ActiveTabIndex == 1)
        {
            LoadFlickerImages();
        }
        if (MainTabContainer.ActiveTabIndex == 2)
        {
            LoadPicasaImages();
        }
    }

    protected void GoToVideosTabImageButton_Click(object sender, ImageClickEventArgs e)
    {
        this.MainTabContainer.ActiveTabIndex = 3;
    }
    protected void Label4_Click(object sender, EventArgs e)
    {
        this.MainTabContainer.ActiveTabIndex = 1;
        ActiveTabChanged(sender, e);
    }
    protected void ImagesLabel_Click(object sender, EventArgs e)
    {
        this.MainTabContainer.ActiveTabIndex = 2;
        ActiveTabChanged(sender, e);
    }
}

